package com.motu.vertx.module.utility.commondata;

import com.motu.vertx.module.utility.base.ServerOpenBase;
import com.motu.vertx.module.utility.base.ServerOpenInterFace;
import com.motu.vertx.module.utility.base.ServerTypeEnum;
import com.motu.vertx.module.utility.main.MainService;
import com.motu.vertx.module.utility.toolset.TimeUtils;
import com.motu.vertx.module.utility.toolset.Tool;
import io.vertx.core.Future;
import io.vertx.core.eventbus.EventBus;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

// 预约开服的配置
public class ServerOpenTask implements Runnable, Delayed {
    private static Logger logger = LoggerFactory.getLogger(ServerOpenTask.class);

    private int serverNum;// 开服数量
    private int openTime;// 开服时间


    public ServerOpenTask(int serverNum, int openTime){
        this.serverNum = serverNum;
        this.openTime = openTime;
    }

    public void run() {
        logger.info("##serveropen task opentime:" + TimeUtils.getTimeFullStr(this.openTime) + " servernum:" + this.serverNum);
        String gmAdress = ServerOpenBase.gmAdress;
        EventBus eventBus = ServerOpenBase.getVertxInstance().eventBus();
        JsonObject message = new JsonObject();
        message.put("cmd", "gm.cmd.server.open");// 通知开服。预约开服
        JsonObject data = new JsonObject();
        data.put("num", this.serverNum);// 开服数量
        data.put("servertype", new JsonArray().add(ServerTypeEnum.WEB.value));// 只有web进程执行
        message.put("data", data);
        logger.info("###send server open cmd event:" + gmAdress + " message:" + message.toString());
        eventBus.publish(gmAdress, message);// 广播所有的进程
    }

    public long getDelay(TimeUnit unit) {
        return unit.convert(openTime - TimeUtils.getCurTime(), TimeUnit.SECONDS);
    }

    public int compareTo(Delayed o) {
        ServerOpenTask that = (ServerOpenTask) o;
        return openTime > that.openTime ? 1 : (openTime < that.openTime ? -1 : 0);
    }

    public long getServerNum(){
        return this.serverNum;
    }

    public int getOpenTime(){
        return this.openTime;
    }
}